<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @keyup.enter.native="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" border stripe style="width:100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-tooltip :enterable="false" content="编辑" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="editUser(scope.row.id)"
                size="mini"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteUser(scope.row.id)"
                size="mini"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" content="分配角色" placement="top">
              <el-button type="primary" icon="el-icon-setting" @click="allotRights(scope.row)" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加弹出对话框 -->
    <el-dialog title="提示" @close="addFormClose" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="提示" :visible.sync="editdialogVisible" @close="editFormClose" width="30%">
      <el-form
        :model="editForm"
        :rules="editrules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击设置弹出对话框 -->
    <el-dialog title="提示" :visible.sync="allotDialogVisible" width="30%">
      <div>
        <p>用户名称：{{userInfo.username}}</p>
        <p>用户角色：{{userInfo.role_name}}</p>
        <p>分配的角色：
          <el-select v-model="roleId" placeholder="请选择">
            <el-option
              v-for="item in roleoptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 获取邮箱的验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        // 邮箱合法
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // 获取手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        // 手机号合法
        return cb()
      }
      cb(new Error('手机号格式错误'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      userList: [],
      addDialogVisible: false,
      editdialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: [],
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 添加编辑用户验证规则
      editrules: {
        email: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框显示
      allotDialogVisible:false,
      // 通过作用域插槽存放当前行的用户信息
      userInfo:{},
      // settting按钮下用来存储分配的角色
      roleId:'',
      roleoptions:[]
    }
  },
  methods: {
    // 分配权限
    async allotRights(scope) {
      this.userInfo = scope
      // 查询所有的角色列表
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      this.roleoptions = res.data
      // console.log(this.roleoptions);
      
      this.allotDialogVisible=true

    },
    // 点击确定之后分配权限
    async updateRoleInfo(){
      // console.log(this.userInfo.id);
      
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.roleId
      })
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.allotDialogVisible = false
      
    },
    async deleteUser(id) {
      var makesure = await this.$confirm('确认删除吗？', '友情提醒', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '放弃删除'
      }).catch(err => err)
      console.log(makesure)
      if (makesure == 'cancel') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'users/' + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            this.editdialogVisible = false
            return
          }
          this.$message.success(res.meta.msg)
          this.editdialogVisible = false
          this.getUserList()
        }
      })
    },
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    async editUser(id) {
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm = res.data
      console.log(this.editForm)

      this.editdialogVisible = true
    },
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 验证通过，就可以发起请求了
        var { data: res } = await this.$http.post('/users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUserList()
      console.log(this.queryInfo.pagesize)
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
      console.log(currentPage)
    },
    async userStateChange(row) {
      // console.log(row.mg_state);
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error(res.meta.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>